package com.zhouxianglh.p19;

/**
 * 19. 删除链表的倒数第N个节点
 * <p>
 * 双指针,一个遍历,另一个记录n-1位置,遍历完后删除下一节点
 *
 * @author zhouxianglh
 */
public class Solution {
    public static void main(String[] args) {
        System.out.println();
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (n == 0 || null == head) {
            return head;
        }
        //
        ListNode nodeN = null;
        ListNode node = head;
        int flag = 0;
        while (null != node) {
            flag++;
            if (flag == (n + 1)) {
                nodeN = head;
            } else if (flag > (n + 1)) {
                nodeN = nodeN.next;
            }
            node = node.next;
        }
        if (null == nodeN) {
            return head.next;
        }
        ListNode nextNode = nodeN.next;
        nodeN.next = nextNode.next;
        return head;
    }

    public static class ListNode {
        int val;

        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

}
